package com.hpradip.android.documentaryHub;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class DetailedInfo extends Activity {

	private DocumentaryFeed feed;
	private static final String YOUTUBE_PLAYLIST_ATOM_FEED_URL = "http://gdata.youtube.com/feeds/api/playlists/";
	private static final int CUSTOM_VARIABLE_PLAY_VIDEO = 1;
	protected static final int CUSTOM_VARIABLE_CANT_PLAY_VIDEO = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		DocumentaryHub.tracker.trackPageView("/"
				+ this.getClass().getSimpleName());

		setContentView(R.layout.detailed_info);
		// WebView webView = (WebView)findViewById(R.id.webview);
		// webView.loadUrl(intent.getExtras().getString("URL"));

		feed = DataProvider.SelectedFeed;

		TextView title_view = (TextView) findViewById(R.id.title);
		title_view.setText(feed.getTitle());

		TextView date_view = (TextView) findViewById(R.id.date);
		date_view.setText(feed.getDate());

		TextView category_view = (TextView) findViewById(R.id.category);
		category_view.setText("Categories: " + feed.getCategory());

		if (feed.getVideoDetails() == null) {
			VideoDetails videoDetails = GetVideoDetails(feed.getLink());
			feed.setVideoDetails(videoDetails);
		}

		Button playButton = (Button) findViewById(R.id.btn_play);
		playButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DocumentaryHub.tracker.trackEvent("UserActions", // Category
						"Play", // Action
						"total", // Label
						1); // Value

				if (feed.getVideoDetails().getVideoUrl() == null) {
					Toast.makeText(DetailedInfo.this, "Can not play video",
							Toast.LENGTH_SHORT).show();
					
					DocumentaryHub.tracker.setCustomVar(
							CUSTOM_VARIABLE_CANT_PLAY_VIDEO,
							"Could Not Play Video", feed.getLink());
					return;
				}
				PlayVideo(feed.getVideoDetails().getVideoUrl());
			}
		});

		TextView desc_view = (TextView) findViewById(R.id.description);
		desc_view.setText(feed.getDescription());

		WebView web_view = (WebView) findViewById(R.id.webview);
		WebSettings settings = web_view.getSettings();
		settings.setBlockNetworkImage(false);
		settings.setBlockNetworkLoads(false);
		settings.setLoadsImagesAutomatically(true);
		String htmlData = feed.getRawHTMLData();
		htmlData = htmlData.replace("Watch now...", "");

		String desc = htmlData;
		if (feed.getVideoDetails() != null)
			desc = feed.getVideoDetails().getSummary();

		web_view.loadDataWithBaseURL(null, desc, "text/html", "UTF-8", null);
		// desc_view.setMovementMethod(LinkMovementMethod.getInstance());

	}

	private void PlayVideo(String uri) {
		// uri = uri.replace("embed/", "watch?v=");
		DocumentaryHub.tracker.setCustomVar(CUSTOM_VARIABLE_PLAY_VIDEO,
				"VideoPlayed", uri);
		String videoId = null;
		boolean isList = false;
		try {
			List<NameValuePair> queryParameters = URLEncodedUtils.parse(
					new URI(uri), "utf-8");

			for (NameValuePair nameValuePair : queryParameters) {
				if ("list".equals(nameValuePair.getName())) {
					videoId = nameValuePair.getValue();
					isList = true;
				}
			}
			
			String path = new URI(uri).getRawPath();
			
			if (!isList && path.contains("embed/")) {
				 videoId = path.split("embed/")[1];
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		if (videoId == null)
			intent.setData(Uri.parse(uri));
		else {
			String youTubeUrl = "http://www.youtube.com/watch?v=";
			if (isList) {
				String firstVideoId = getFirstPlaylistVideo(videoId);
				youTubeUrl = "http://www.youtube.com/watch?v=" + firstVideoId
						+ "&autoplay=1&list=";
			}
			intent.setData(Uri.parse(youTubeUrl + videoId));
		}

		try {
			startActivity(intent);
		} catch (ActivityNotFoundException ex) {
			intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse(uri));
			startActivity(intent);
		}
	}

	private String getFirstPlaylistVideo(String pPlaylistId) {
		if (pPlaylistId.startsWith("PL"))
			pPlaylistId = pPlaylistId.replace("PL", "");
		String lVideoId = null;

		HttpClient lClient = new DefaultHttpClient();

		HttpGet lGetMethod = new HttpGet(YOUTUBE_PLAYLIST_ATOM_FEED_URL
				+ pPlaylistId + "?v=2&max-results=50&alt=json");

		HttpResponse lResp = null;

		try {
			lResp = lClient.execute(lGetMethod);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			return null;
		}

		ByteArrayOutputStream lBOS = new ByteArrayOutputStream();
		String lInfoStr = null;
		JSONObject lYouTubeResponse = null;

		try {

			lResp.getEntity().writeTo(lBOS);
			lInfoStr = lBOS.toString("UTF-8");
			lYouTubeResponse = new JSONObject(lInfoStr);

			JSONArray lEntryArr = lYouTubeResponse.getJSONObject("feed")
					.getJSONArray("entry");
			JSONArray lLinkArr = lEntryArr.getJSONObject(0)
					.getJSONArray("link");
			for (int i = 0; i < lLinkArr.length(); i++) {
				JSONObject lLinkObj = lLinkArr.getJSONObject(i);
				;
				String lRelVal = lLinkObj.optString("rel", null);
				if (lRelVal != null && lRelVal.equals("alternate")) {

					String lUriStr = lLinkObj.optString("href", null);
					Uri lVideoUri = Uri.parse(lUriStr);
					lVideoId = lVideoUri.getQueryParameter("v");
					break;
				}
			}
		} catch (IllegalStateException e) {
			Log.i(getClass().getSimpleName(),
					"Error retrieving content from YouTube", e);
		} catch (IOException e) {
			Log.i(getClass().getSimpleName(),
					"Error retrieving content from YouTube", e);
		} catch (JSONException e) {
			Log.i(getClass().getSimpleName(),
					"Error retrieving content from YouTube", e);
		}

		return lVideoId;
	}

	public VideoDetails GetVideoDetails(String link) {
		String uri = null;
		String summary = null;

		try {
			URL url = new URL(link);
			// InputSource is = new InputSource(url.openStream());
			// DocumentBuilder documentBuilder = DocumentBuilderFactory
			// .newInstance().newDocumentBuilder();
			// InputStreamReader reader = new
			// InputStreamReader(url.openStream());

			org.jsoup.nodes.Document doc = Jsoup.parse(url, 3000);

			summary = getVideoSummary(doc);

			Elements iframe = doc.select("iframe");
			uri = iframe.attr("src");

			if (uri == null || uri.length() == 0) {

				Elements embed = doc.select("embed");
				uri = embed.attr("src");
			}

			// Document dom = documentBuilder.parse(is);
			// Element root = dom.getDocumentElement();
			// NodeList frames = root.getElementsByTagName("iframe");
			//
			// for (int i = 0; i < frames.getLength(); i++) {
			// Node frame = frames.item(i);
			// NamedNodeMap attributes = frame.getAttributes();
			// if(attributes!=null){
			// Node item = attributes.getNamedItem("src");
			// if(item!=null)
			// {
			// uri = item.getNodeValue();
			// break;
			// }
			// }
			// }

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// catch (ParserConfigurationException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (SAXException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

		return new VideoDetails(uri, summary);
	}

	private String getVideoSummary(Document doc) {
		List<Element> discElements = new ArrayList<Element>();
		try {
			boolean started = false;
			Elements selectedElements = doc.select("p");
			for (int i = 0; i < selectedElements.size(); i++) {
				Element element = selectedElements.get(i);
				if (element.children().size() > 0) {
					if (element.children().get(0).tagName() == "img"
							&& !started)
						started = true;
					else if (element.children().get(0).tagName() == "strong"
							&& started) {

						if (element.children().get(0).text()
								.startsWith("Watch the full documentary now")) {
							StringBuilder sb = new StringBuilder();
							for (Element element2 : discElements) {
								sb.append(element2.outerHtml());
							}
							return sb.toString();
						}
					}
				}
				if (started) {
					discElements.add(element);
				}
			}
		} catch (Exception ex) {
			Log.d(DocumentaryHub.TAG, ex.getMessage());
		}
		return null;
	}

	@Override
	protected void onResume() {
		DocumentaryHub.tracker.trackPageView("/"
				+ this.getClass().getSimpleName());
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		DocumentaryHub.tracker.dispatch();
		super.onDestroy();
	}

}
